package com.rg.inf.action;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.zip.GZIPInputStream;

import org.apache.commons.fileupload.FileItem;

import baseproj.component.log.LoggerAdapter;
import baseproj.component.log.LoggerService;

import com.rd.sys.common.utils.client.AnalysisPathUtils;
import com.rd.sys.dto.client.sync.FileMaterialMsgBody;
import com.rd.sys.dto.client.sync.MsgBody;
import com.rd.sys.dto.commmon.base.EyeException;
import com.rd.sys.dto.commmon.base.EyeResult;
import com.rd.sys.dto.sys.user.UserInfoDto;

public class FileMaterialSyncAction extends BaseExecuteAction {
    protected final static LoggerService logger = LoggerAdapter.getLoggerService(FileMaterialSyncAction.class);

    @Override
    public EyeResult execute(UserInfoDto userInfo, MsgBody msgBody, Object... objs) throws EyeException, Exception {
        FileMaterialMsgBody body = (FileMaterialMsgBody) msgBody;
        List<FileItem> fileItems = (List<FileItem>) objs[0];

        /** 1.获取文件保存目录 */
        String path = AnalysisPathUtils.findSchemePath(userInfo.getUsercode(), body.getProjectCode(),
                body.getSchemeCode());

        /** 2.逐个保存文件 */
        Iterator<FileItem> it = fileItems.iterator();

        GZIPInputStream in = null; // 客户端上传的文件是gzip压缩的
        FileOutputStream out = null;

        while (it.hasNext()) {
            try {
                FileItem item = it.next();
                File uploadFile = new File(item.getName());
                File savedFile = new File(path, uploadFile.getName());

                in = new GZIPInputStream(item.getInputStream());
                out = new FileOutputStream(savedFile);
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }

            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception ex) {
                        logger.error("", ex);
                    }
                    out = null;
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception ex) {
                        logger.error("", ex);
                    }
                    in = null;
                }
            }
        }

        return new EyeResult(EyeResult.ResultDefine.COMMON_SUCCESS);
    }
}
